<template>
  <div class="app-container calendar-list-container">
    <!--功能-->
    <div class="filter-container">
      <el-row>
        <el-col :span="12">
          <el-button type="primary" icon="el-icon-plus" @click="editBtn('新增',selectOneRow)">新增</el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="importData" icon="el-icon-upload2">导入
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="modifyStoreArea('location', '0')" icon="el-icon-edit">禁用
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="modifyStoreArea('location', '1')" icon="el-icon-edit">启用
          </el-button>
          <el-button type="primary" icon="el-icon-edit" @click="changeType">批量修改库位类型</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-input size="small" style="width: 200px" class="filter-item fsc-search" placeholder="库区名称-回车查询" v-model="listQuery.condition.storeAreaName" @keyup.enter.native="search"></el-input>
          <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-search" @click="search">
            搜索
          </el-button>
          <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-circle-plus-outline" @click="moreClick">更多
          </el-button>
          <el-dropdown trigger="click" :hide-on-click=false style="float: right;margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button class="filter-item" size="small" type="primary" v-waves>
                选择列
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-checkbox-group v-model="tHeadCheckVal">
                  <el-checkbox label="storeHouseName">仓库</el-checkbox>
                  <el-checkbox label="storeAreaName">库区</el-checkbox>
                  <el-checkbox label="code">库位编码</el-checkbox>
                  <el-checkbox label="name">库位名称</el-checkbox>
                  <el-checkbox label="type">库位类型</el-checkbox>
                  <el-checkbox label="sort">分配排序</el-checkbox>
                  <el-checkbox label="maxStorage">最大存储量</el-checkbox>
                  <el-checkbox label="status">状态</el-checkbox>
                  <el-checkbox label="remark">备注</el-checkbox>
                </el-checkbox-group>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
    </div>
    <!--查询条件-->
    <el-form class="web_form" :inline="true" v-show="searchFlag" :class="{'web_form_active': searchFlag }" label-width="100px" style="margin: 6px 0 0 10px">
      <el-form-item label=库位类型:>
        <el-select v-model="listQuery.condition.type" class="w100" clearable filterable remote reserve-keyword placeholder="请选择库区类型">
          <el-option v-for="(item,index) in formWays.type" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=库位状态:>
        <el-select v-model="listQuery.condition.status" class="w100" clearable filterable remote reserve-keyword placeholder="请选择库位状态">
          <el-option v-for="(item,index) in formWays.status" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" style="margin-left: 10px">查询</el-button>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <!--主列表-->
    <el-table ref="storeLocationTable" :data="storeLocationList" v-loading="listLoading" element-loading-text="加载中" border fit highlight-current-row
              style="width: 100%;margin-top:5px"
              @select="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
      <el-table-column :key="key" align="center" :width="value.width" v-for='(value,key) in tableHead' :label="value.title">
        <template slot-scope="scope">
          <div v-if="value.key === 'type'">{{scope.row[value.key] | storeLocationTypeFilter}}</div>
          <div v-else-if="value.key === 'status'">{{scope.row[value.key] | storeLocationStatusFilter}}</div>
          <div v-else>{{scope.row[value.key]}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button type="info" size="mini" class="btn-edit" @click="editBtn('查看',scope.row)">查看</el-button>
          <el-button type="primary" size="mini" class="btn-delete" @click="editBtn('编辑',scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      v-show="!listLoading"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="listQuery.current"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listQuery.total">
    </el-pagination>
    <!--导入面板-->
    <el-dialog title="库位导入" :visible.sync="importDialogVisible" width="75%" :before-close="handleClose">
      <upload-excel-component @on-selected-file='selected'></upload-excel-component>
      <el-button @click="importDialogVisible = false">取 消</el-button>
      <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary"
                 v-waves icon="el-icon-upload2" @click="confirmImport" :disabled="importLoading">导入</el-button>
      <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item in tableHeader" :prop="item" :label="item" :key='item ' :show-overflow-tooltip="true"></el-table-column>
      </el-table>
    </el-dialog>
    <!---编辑面板-->
    <store-location-edit
      :edit_flag="editFlag"
      :edit_params="editParams"
      :edit_main_title="editMainTitle"
      :edit_select_row="editRowData"
      ref="storeLocationEditRef"
      @edit-confirm="editConfirm"
      @edit-close="editClose">
    </store-location-edit>
    <!--修改库位类型 面板-->
    <store-type-edit
      :edit_flag="storeTypeFlag"
      :edit_params="storeTypeParams"
      :edit_main_title="storeTypeMainTitle"
      :edit_select_row="storeTypeRowData"
      ref="storeTypeEditRef"
      @edit-confirm="storeTypeConfirm"
      @edit-close="storeTypeClose">
    </store-type-edit>
  </div>
</template>
<script>
  import UploadExcelComponent from '@/components/UploadExcel/index.vue'
  import StoreLocationEdit from './storeLocationConfig/storeLocationEdit'
  import StoreTypeEdit from './storeLocationConfig/storeTypeEdit'
  import * as StoreLocationAPI from '@/api/house/storeLocation'
  import * as StoreAreaAPI from '@/api/house/storeArea'
  import waves from '@/directive/waves' // 水波纹指令
  const defaultTableHead = [
    { key: 'storeHouseName', title: '仓库', width: '' },
    { key: 'storeAreaName', title: '库区', width: '' },
    { key: 'code', title: '库位编码', width: '' },
    { key: 'name', title: '库位名称', width: '' },
    { key: 'type', title: '库位类型', width: '' },
    { key: 'sort', title: '分配排序', width: '' },
    { key: 'maxStorage', title: '最大存储量', width: '' },
    { key: 'status', title: '状态', width: '' },
    { key: 'remark', title: '备注', width: '' }
  ]
  export default {
    components: { UploadExcelComponent, StoreLocationEdit, StoreTypeEdit },
    name: 'storeLocation',
    directives: { waves },
    data() {
      return {
        tHeadCheckVal: ['id', 'storeHouseId', 'storeHouseName', 'storeAreaId', 'storeAreaName', 'code', 'name', 'type', 'sort', 'maxStorage', 'status', 'remark'],
        editObj: {},
        tableHead: defaultTableHead,
        listQuery: {
          current: 1,
          size: 10,
          total: 0,
          condition: {}
        },
        storeLocationList: [],
        multipleSelection: [],
        listLoading: true,
        importDialogVisible: false, // 导入面板 显示 隐藏
        importLoading: false,  // 导入面板 loading
        tableData: [],
        tableHeader: [],
        searchFlag: true,
        formWays: {
          type: [
            { value: '10', label: '普通库位' },
            { value: '20', label: '临时库位' },
            { value: '30', label: '虚拟库位' },
            { value: '40', label: '大库位' },
            { value: '50', label: '中库位' }
          ],
          status: [
            { value: '10', label: '正常' },
            { value: '20', label: '失效' }
          ]
        },
        houseName: this.$store.getters.currentStorehouse.name,
        selectOneRow: {},
        editFlag: false, // 库位修改 面板 显示
        editParams: {}, // 库位修改 面板 自定义传参
        editRowData: {}, // 传入 库位修改 面板 当前列
        editMainTitle: '', // 库位修改 面板 标题
        storeTypeFlag: false, // 库位修改 面板 显示
        storeTypeParams: {}, // 库位修改 面板 自定义传参
        storeTypeRowData: {}, // 传入 库位修改 面板 当前列
        storeTypeMainTitle: '' // 库位修改 面板 标题
      }
    },
    created() {
      this.getList()
    },
    watch: {
      tHeadCheckVal(valArr) {
        this.tableHead = defaultTableHead.filter(v => {
          for (var i = 0; i < valArr.length; i++) {
            if (v.key === valArr[i]) {
              return v
            }
          }
        })
      }
    },
    methods: {
      // 库位修改面板 显示
      changeType() {
        const that = this
        if (that.checkSelect(that.multipleSelection)) {
          const ids = that.multipleSelection.map(item => {
            return item.id
          })
          that.storeTypeRowData = {}
          that.storeTypeMainTitle = '修改库位类型'
          that.storeTypeParams = { ids }
          that.storeTypeFlag = true
        }
      },
      // 库位修改面板 确认
      storeTypeConfirm() {
        this.search()
        this.storeTypeFlag = false
      },
      // 库位修改面板 弹窗关闭
      storeTypeClose() {
        this.storeTypeFlag = false
      },
      // 新增  编辑  查看
      editBtn(editTitle, row) {
        const that = this
        that.editRowData = row
        that.editMainTitle = editTitle
        that.editParams = {
          houseName: that.houseName
        }
        that.editFlag = true
      },
      // 编辑面板 确认
      editConfirm() {
        this.search()
        this.editFlag = false
      },
      // 编辑面板 弹窗关闭
      editClose() {
        this.editFlag = false
      },
      // 导入面板 显示
      importData() {
        this.importDialogVisible = true
      },
      confirmImport() {
        // 确定导入  转换列名字
        const data = {
          storeHouseId: this.$store.getters.currentStorehouse.id,
          header: this.tableHeader,
          rows: this.tableData
        }
        this.importLoading = true
        StoreLocationAPI.importLocationInit(data).then(result => {
          if (result.code === 0) {
            this.tableHeader = result.data.header
            this.tableData = result.data.rows
          } else {
            this.$message({
              title: '错误提示',
              message: result.message,
              type: 'error',
              duration: 2000
            })
          }
          this.importLoading = false
        })
      },
      // 导入面板 关闭
      handleClose() {
        this.importDialogVisible = false
        this.tableData = []
        this.tableHeader = []
        this.getList()
      },
      selected(data) {
        this.tableData = data.results
        this.tableHeader = data.header
      },
      // type area ：表示库区 ；location：表示库位, handleType 0：表示禁用，1：表示取消禁用
      modifyStoreArea(type, handleType) {
        const that = this
        const field = 'status' // 验证字段
        let c = ''
        let d = '' // field 的数据状态
        if (handleType === '0') {
          c = '禁用'
          d = '20'
        }
        if (handleType === '1') {
          c = '启用'
          d = '10'
        }
        if (that.checkModifySelect(that.multipleSelection, d, field, c)) {
          const keyList = that.multipleSelection.map(item => item.id)
          const toParams = {
            keys: keyList.join(','),
            type,
            handleType
          }
          StoreAreaAPI.batchUpdateStatus(toParams).then(result => {
            this.$message({
              title: '提示',
              message: '批量' + c + '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch((err) => {
            console.log('error', err)
          })
        }
      },
      // 检查是否选择单条
      checkModifySelect(selectRow, handleType, field, msg) {
        const l = selectRow.length
        if (l === 0) {
          this.$message({
            message: '未选择',
            type: 'warning',
            duration: 2000
          })
          return false
        }
        const b = selectRow.some(item => item[field] === handleType)
        if (b) {
          this.$message({
            message: '选中项有已' + msg + '项，不能进行' + msg,
            type: 'warning',
            duration: 2000
          })
          return false
        }
        return true
      },
      // 查询
      getList() {
        // 列表查询
        this.listLoading = true
        // 处理是否展开更多
        let queryParam = {}
        if (this.$data.searchFlag) {
          queryParam = this.$data.listQuery
        } else {
          Object.assign(queryParam, this.$data.listQuery)
          queryParam.condition = {
            storeAreaName: this.$data.listQuery.condition.storeAreaName
          }
        }
        queryParam.condition.storeHouseId = this.$store.getters.currentStorehouse.id
        // console.log('queryLocationByPage()-currentStorehouse', this.$store.getters.currentStorehouse.name)
        this.houseName = this.$store.getters.currentStorehouse.name
        StoreLocationAPI.queryLocationByPage(queryParam).then(result => {
          if (result.code === 0) {
            this.$data.storeLocationList = result.data.records
            this.$data.listQuery.total = result.data.total
            if (this.$data.storeLocationList && this.$data.storeLocationList.length >= 1) {
              this.houseName = this.$data.storeLocationList[0].storeHouseName
            }
            this.listLoading = false
          } else {
            this.listLoading = false
            this.$notify({
              title: '信息提示',
              message: result.message,
              type: 'error',
              duration: 2000
            })
          }
        }).catch(() => {
          this.listLoading = false
          this.$data.storeLocationList = null
        })
      },
      // 检查是否选择
      checkSelect(data) {
        const l = data.length
        if (l === 0) {
          this.$message({
            message: '未选择',
            type: 'warning',
            duration: 2000
          })
          return false
        }
        // if (l > 1) {
        //   this.$message({
        //     message: '请只选择一条数据',
        //     type: 'warning',
        //     duration: 2000
        //   })
        //   return false
        // }
        return true
      },
      // 分页size变化
      handleSizeChange(val) {
        this.$data.listQuery.size = val
        this.getList()
      },
      // 分页当前页变化
      handleCurrentChange(val) {
        this.$data.listQuery.current = val
        this.getList()
      },
      // 选中项
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更多
      moreClick() {
        this.$data.searchFlag = !this.$data.searchFlag
      },
      // 搜索
      search() {
        this.getList()
      },
      // 重置
      resetSearch() {
        this.$data.listQuery.condition = {
          houseId: this.$store.getters.currentStorehouse.id,
          storeAreaName: null,
          type: null,
          status: null
        }
        this.getList()
      }
    }
  }
</script>
<style type="text/scss" lang="scss" scoped>
</style>
